<?php
namespace Admin\Model;
use Think\Model;
class NewsModel extends Model {
  protected $_validate = array(
    //菜单添加修改的正则表达式 
    array('news_name','require','新闻名称不能为空',0,'regex',3),    
    array('news_title','require','新闻标题一不能为空',0,'regex',3),    
    array('news_titles','require','新闻标题二不能为空',0,'regex',3),       
    array('news_contro','require','新闻简介不能为空',0,'regex',3),
    array('news_content','require','新闻内容不能为空',0,'regex',3),        
    array('news_url','require','跳转地址不能为空',0,'regex',3),        

  );

  //文件上传
  public function fileUpload(){
    //实现文件上传
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728 ;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Public/Uploads/'; // 设置附件上传目录
        //如果没有目录,则创建一个目录
        if(!is_dir($upload->rootPath)){
          mkdir($upload->rootPath);
        }
        $info = $upload->upload();
        if(!$info) {
        // 上传错误提示错误信息        
        $this->error($upload->getError()); 
        return false;   
        }else{
        // 上传成功        
        return $info;

        }
  }

  // 插入数据前的回调方法
  protected function _before_insert(&$data,$options) {
    //dump($_FILES);die;
    $data['add_time'] = time();
    //判断有没有上传文件
    if($_FILES['news_images']['error']==0){
      $uploadInfo=$this->fileUpload();
      //dump($uploadInfo);die;
      if($uploadInfo===false){
        return false;
      }else{       
        $data['news_images']=$uploadInfo['news_images']['savepath'].$uploadInfo['news_images']['savename'];

      }
    }

  }
   // 插入数据前的回调方法
  protected function _before_update(&$data,$options) {
    $data['add_time'] = time();  
  }
}